﻿Public Class File_IO
#Region "Folders"
    Public Shared Function GetFolders(ByVal FolderPath As String, ByVal FolderName As String) As List(Of ServerFolder)
        Dim FolderList As New List(Of ServerFolder)()
        Dim folder As New DirectoryInfo(FolderPath & FolderName)
        For Each aFolder In folder.GetDirectories()
            Dim objFolder As New ServerFolder() With { _
                .ParentFolderid = aFolder.Parent.Name, _
                .FolderName = aFolder.Name, _
                .CreationDate = aFolder.CreationTime, _
                .ModifiedDate = aFolder.LastWriteTime}
            FolderList.Add(objFolder)
        Next
        Return FolderList
    End Function
    Public Shared Function AddFolder(ByVal FolderPath As String, ByVal Foldername As String) As String
        Dim response As String = "return from add folder"
        Try
            Dim di As New DirectoryInfo(Path.Combine(FolderPath, Foldername))
            If di.Exists Then
                Throw New MyCustomException("Folder not added, folder already exists")
            Else
                di.Create()
                ' Success
                Return "Folder added"
            End If
        Catch MyCE As MyCustomException
            Throw MyCE
        Catch ex As Exception
            Dim errStr As String = "Error with path:" & FolderPath & " -- name:" & Foldername
            Logging.LogError(ex, ex.Message)
            Logging.DebugLog(errStr)
            response = "Error" & errStr
            Throw New Exception(response, ex)
        End Try
        Throw New MyCustomException("Unhandled error: " & response)
    End Function
    Public Shared Function DeleteFolder(ByVal FolderPath As String, ByVal Foldername As String) As String
        Dim response As String = "Return from delete folder"
        Try
            'FolderPath = FolderPath.Replace(Foldername, "")
            Dim di As New DirectoryInfo(Path.Combine(FolderPath, Foldername))
            If di.Exists Then
                di.Delete(True)
                ' Success
                Return "Folder deleted"
            Else
                Throw New MyCustomException("Folder not deleted, folder not found")
            End If
        Catch MyCE As MyCustomException
            Throw MyCE
        Catch ex As Exception
            Dim errStr As String = "Error with path:" & FolderPath & " -- name:" & Foldername
            Logging.LogError(ex, ex.Message)
            Logging.DebugLog(errStr)
            response = "Error" & errStr
            Throw New Exception(response, ex)
        End Try
        Throw New MyCustomException("Unhandled error: " & response)
    End Function
    Public Shared Function UpdateFolder(ByVal FolderPath As String, ByVal OrigFolderName As String, ByVal NewFolderPath As String, ByVal NewFolderName As String) As String
        Dim response As String = "Return from update folder"
        Try
            'FolderPath = FolderPath.Replace(OrigFolderName, "")
            Dim di As New DirectoryInfo(Path.Combine(FolderPath, OrigFolderName))
            Dim diNew As New DirectoryInfo(Path.Combine(NewFolderPath, NewFolderName))
            If di.Exists Then
                If diNew.Exists Then
                    Throw New MyCustomException("Folder not updated, new folder already exists")
                Else
                    di.MoveTo(Path.Combine(NewFolderPath, NewFolderName))
                    ' Success
                    Return "Folder updated"
                End If
            Else
                Throw New MyCustomException("Folder not updated, old folder not found")
            End If
        Catch MyCE As MyCustomException
            Throw MyCE
        Catch ex As Exception
            Dim errStr As String = "Error with path:" & FolderPath & " -- oldname:" & OrigFolderName & " -- newname:" & NewFolderName & " -- newfolers:" & NewFolderPath
            Logging.LogError(ex, ex.Message)
            Logging.DebugLog(errStr)
            response = "Error" & errStr
            Throw New Exception(response, ex)
        End Try
        Throw New MyCustomException("Unhandled error: " & response)
    End Function
#End Region
#Region "Files"
    Public Shared Function GetFiles(ByVal FolderPath As String, ByVal FileName As String) As List(Of ServerFile)
        Dim FileList As New List(Of ServerFile)()
        Dim dir As New DirectoryInfo(FolderPath & FileName)
        For Each aFile In dir.GetFiles
            Dim objFile As New ServerFile() With { _
                .FullPath = aFile.DirectoryName.ToString, _
                .FileName = aFile.Name, _
                .CreationDate = aFile.CreationTime, _
                .ModifiedDate = aFile.LastWriteTime}
            FileList.Add(objFile)
        Next
        Return FileList
    End Function
    Public Shared Function DeleteFile(ByVal FolderPath As String, ByVal FileName As String) As String
        Dim response As String = "return from delete"
        Try
            Dim fi As New FileInfo(Path.Combine(FolderPath, FileName))
            If fi.Exists Then
                fi.Delete()
                ' Success
                Return "File deleted"
            Else
                Throw New MyCustomException("File not deleted, folder not found")
            End If
        Catch MyCE As MyCustomException
            Throw MyCE
        Catch ex As Exception
            Dim errStr As String = "Error with path:" & FolderPath & " -- name:" & FileName
            Logging.LogError(ex, ex.Message)
            Logging.DebugLog(errStr)
            response = "Error" & errStr
            Throw New Exception(response, ex)
        End Try
        Throw New MyCustomException("Unhandled error: " & response)
    End Function
    Public Shared Function UpdateFile(ByVal FolderPath As String, ByVal OrigFileName As String, ByVal NewFolderPath As String, ByVal NewFileName As String) As String
        Dim response As String = "return from update file"
        Try
            Dim fi As New FileInfo(Path.Combine(FolderPath, OrigFileName))
            Dim fiNew As New FileInfo(Path.Combine(NewFolderPath, NewFileName))
            If fi.Exists Then
                If fiNew.Exists Then
                    Throw New MyCustomException("File not updated, new file already exists")
                Else
                    fi.MoveTo(Path.Combine(NewFolderPath, NewFileName))
                    ' Success
                    Return "File updated"
                End If
            Else
                Throw New MyCustomException("File not updated, old file not found")
            End If
        Catch MyCE As MyCustomException
            Throw MyCE
        Catch ex As Exception
            Dim errStr As String = "Error with path:" & FolderPath & " -- oldname:" & OrigFileName & " -- newname:" & NewFileName & " -- newfolderpath:" & NewFolderPath
            Logging.LogError(ex, ex.Message)
            Logging.DebugLog(errStr)
            response = "Error" & errStr
            Throw New Exception(response, ex)
        End Try
        Throw New MyCustomException("Unhandled error: " & response)
    End Function
#End Region
#Region "Extra"
    ''' <summary>
    ''' Find all files in a directory, and all files within every nested
    ''' directory.
    ''' from: http://dotnetperls.com/Content/Recursively-Find-Files.aspx
    ''' </summary>
    ''' <param name="baseDir">The starting directory you want to use.</param>
    ''' <returns>A string array containing all the file names.</returns>
    Public Shared Function GetAllFileNames(ByVal baseDir As String) As String()
        ' Store results in the file results list.
        Dim fileResults As New List(Of String)()
        ' Store a stack of our directories.
        Dim directoryStack As New Stack(Of String)()
        directoryStack.Push(baseDir)
        ' While there are directories to process and we don't have too many results
        While directoryStack.Count > 0 AndAlso fileResults.Count < 1000
            Dim currentDir As String = directoryStack.Pop()
            ' Add all files at this directory.
            For Each fileName As String In Directory.GetFiles(currentDir, "*.*")
                fileResults.Add(fileName)
            Next
            ' Add all directories at this directory.
            For Each directoryName As String In Directory.GetDirectories(currentDir)
                directoryStack.Push(directoryName)
            Next
        End While
        Return fileResults.ToArray()
    End Function
    Public Shared Sub EnsureDirectory(ByVal oDirInfo As System.IO.DirectoryInfo)
        If oDirInfo.Parent IsNot Nothing Then
            EnsureDirectory(oDirInfo.Parent)
        End If
        If Not oDirInfo.Exists Then
            oDirInfo.Create()
        End If
    End Sub
#End Region
End Class